﻿using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Cms.Web.Framework.Infrastructure;

namespace Cms.Web.Framework.Controls
{
    public class AdminBasePage : System.Web.UI.Page
    {
        public string Localization
        {
            get { return ((AdminBaseMaster)Master).Localization; }
            set { ((AdminBaseMaster)Master).Localization = value; }
        }
        
        public void RedirectToPermissionDeniedPage()
        {
            RedirectToPermissionDeniedPage(null);
        }

        public void RedirectToPermissionDeniedPage(string message)
        {
            string url = "~/Admin/PermissionDenied.aspx";
            if (message != null)
                url += "?message=" + Server.UrlEncode(message);
            Response.Redirect(url);
        }

        public void RedirectToBadRequestParameterPage()
        {
            Response.Redirect("~/Admin/BadRequestParameter.aspx");
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            HttpCookie cookie;
            Control control;
            string controlName = Page.Request.Params.Get("__EVENTTARGET");
            if (Page.IsPostBack && !string.IsNullOrEmpty(controlName))
            {
                control = Page.FindControl(controlName);
                if (control != null && control.Parent is Panel && control.Parent.ID == "pnlLocales")
                {
                    Localization = ((LinkButton)control).CommandArgument;
                    cookie = new HttpCookie("FrediumAdminLocalization", Localization) { Expires = DateTime.Now.AddYears(1) };
                    Response.Cookies.Add(cookie);
                }
            }
            if (Page.IsPostBack)
            {
                return;
            }
            cookie = Request.Cookies["FrediumAdminLocalization"];
            if (cookie != null)
            {
                Localization = cookie.Value;
                return;
            }
            if (HttpContext.Current.Items["RequestDetails"] != null)
            {
                var administrator = ((RequestDetails)HttpContext.Current.Items["RequestDetails"]).Administrator;
                if (administrator != null)
                {
                    Localization = administrator.DefaultSystemLocale;
                    cookie = new HttpCookie("FrediumAdminLocalization", Localization) { Expires = DateTime.Now.AddYears(1) };
                    Response.Cookies.Add(cookie);
                    return;
                }
            }
            Localization = "en-US";
        }
    }
}